"""
演示HookHub同步异步在EventBus中的体现
"""

import asyncio
import threading
import time
from event_bus import EventBus as CPPEventBus
from hook_hub import HookHub


# 记录执行时间和顺序
execution_log = []
log_lock = threading.Lock()


def sync_validator(**kwargs):
    """同步验证器 - 阻塞执行"""
    with log_lock:
        execution_log.append(f"[Sync-Validator] 开始验证: {time.time():.3f}")
    
    payload = kwargs.get('payload', '')
    # 模拟验证耗时
    time.sleep(0.5)
    
    is_valid = len(payload) > 0
    with log_lock:
        execution_log.append(f"[Sync-Validator] 验证完成: {time.time():.3f}, 结果: {is_valid}")
    
    # 如果验证失败，阻止事件传播
    if not is_valid:
        with log_lock:
            execution_log.append(f"[Sync-Validator] 阻止事件传播")
        return False
    return True


def sync_processor(**kwargs):
    """同步处理器 - 阻塞执行"""
    with log_lock:
        execution_log.append(f"[Sync-Processor] 开始处理: {time.time():.3f}")
    
    payload = kwargs.get('payload', '')
    # 模拟业务处理耗时
    time.sleep(0.3)
    
    with log_lock:
        execution_log.append(f"[Sync-Processor] 处理完成: {time.time():.3f}")
    return f"Processed: {payload}"


async def async_logger(**kwargs):
    """异步日志记录器 - 非阻塞执行"""
    with log_lock:
        execution_log.append(f"[Async-Logger] 开始记录: {time.time():.3f}")
    
    payload = kwargs.get('payload', '')
    # 模拟异步日志操作
    await asyncio.sleep(1.0)  # 模拟写入数据库
    
    with log_lock:
        execution_log.append(f"[Async-Logger] 记录完成: {time.time():.3f}")
    return "Logged"


async def async_notifier(**kwargs):
    """异步通知器 - 非阻塞执行"""
    with log_lock:
        execution_log.append(f"[Async-Notifier] 开始通知: {time.time():.3f}")
    
    payload = kwargs.get('payload', '')
    # 模拟异步网络请求
    await asyncio.sleep(0.8)  # 模拟发送邮件
    
    with log_lock:
        execution_log.append(f"[Async-Notifier] 通知完成: {time.time():.3f}")
    return "Notified"


class EventBusWithHookHub:
    """EventBus与HookHub结合的演示"""
    
    def __init__(self):
        self.cpp_bus = CPPEventBus()
        self.hook_hub = HookHub()
        self._setup_handlers()
        
    def _setup_handlers(self):
        """设置事件处理器"""
        # 注册C++事件处理器
        self.cpp_bus.on(0xC0, self._forward_to_hookhub)
        
        # 注册HookHub处理器（注意优先级和异步设置）
        self.hook_hub.register("cpp_event", sync_validator, priority=100)  # 高优先级同步验证
        self.hook_hub.register("cpp_event", sync_processor, priority=50)   # 同步业务处理
        self.hook_hub.register("cpp_event", async_logger, priority=10, is_async=True)    # 异步日志
        self.hook_hub.register("cpp_event", async_notifier, priority=5, is_async=True)   # 异步通知
        
    def _forward_to_hookhub(self, payload: str) -> None:
        """将C++事件转发到HookHub"""
        with log_lock:
            execution_log.append(f"[Bridge] 转发事件到HookHub: {time.time():.3f}")
        
        # 在HookHub中处理事件（这里体现同步/异步的区别）
        start_time = time.time()
        self.hook_hub.emit("cpp_event", payload=payload)
        end_time = time.time()
        
        with log_lock:
            execution_log.append(f"[Bridge] HookHub处理完成: {time.time():.3f}, 耗时: {end_time - start_time:.3f}秒")
        
    def emit_event(self, event_id: int, payload: str):
        """发送事件"""
        self.cpp_bus.emit(event_id, payload)
        
    def shutdown(self):
        """关闭"""
        self.cpp_bus.shutdown()


def demonstrate_sync_async_behavior():
    """演示同步异步行为"""
    print("=== 演示HookHub同步异步在EventBus中的体现 ===")
    
    # 创建集成系统
    integrated_system = EventBusWithHookHub()
    
    print("发送测试事件...")
    execution_log.clear()
    
    # 记录开始时间
    start_time = time.time()
    
    # 发送事件
    integrated_system.emit_event(0xC0, "test_data_for_processing")
    
    # 等待一段时间确保所有异步任务完成
    time.sleep(3)
    
    end_time = time.time()
    
    print(f"总处理耗时: {end_time - start_time:.3f}秒")
    
    print("\n执行日志（按时间顺序）:")
    for log_entry in execution_log:
        print(log_entry)
    
    # 分析执行特点
    print("\n=== 执行特点分析 ===")
    
    # 找出同步和异步操作
    sync_ops = [log for log in execution_log if any(sync_tag in log for sync_tag in ["[Sync-Validator]", "[Sync-Processor]", "[Bridge]"])]
    async_ops = [log for log in execution_log if any(async_tag in log for async_tag in ["[Async-Logger]", "[Async-Notifier]"])]
    
    print(f"同步操作 ({len(sync_ops)} 个):")
    for op in sync_ops:
        print(f"  {op}")
        
    print(f"异步操作 ({len(async_ops)} 个):")
    for op in async_ops:
        print(f"  {op}")
    
    # 分析时间线
    print("\n=== 时间线分析 ===")
    timeline_analysis()
    
    # 关闭系统
    integrated_system.shutdown()
    
    print("\n演示完成")


def timeline_analysis():
    """时间线分析"""
    # 提取关键时间点
    bridge_forward = None
    bridge_complete = None
    sync_validator_start = None
    sync_validator_end = None
    sync_processor_start = None
    sync_processor_end = None
    async_logger_start = None
    async_logger_end = None
    
    for log in execution_log:
        if "[Bridge] 转发事件到HookHub" in log:
            bridge_forward = float(log.split(":")[-1].strip()[:-1])
        elif "[Bridge] HookHub处理完成" in log:
            bridge_complete = float(log.split(":")[-1].strip()[:-1])
        elif "[Sync-Validator] 开始验证" in log:
            sync_validator_start = float(log.split(":")[-1].strip()[:-1])
        elif "[Sync-Validator] 验证完成" in log:
            sync_validator_end = float(log.split(":")[-1].strip()[:-1])
        elif "[Sync-Processor] 开始处理" in log:
            sync_processor_start = float(log.split(":")[-1].strip()[:-1])
        elif "[Sync-Processor] 处理完成" in log:
            sync_processor_end = float(log.split(":")[-1].strip()[:-1])
        elif "[Async-Logger] 开始记录" in log:
            async_logger_start = float(log.split(":")[-1].strip()[:-1])
        elif "[Async-Logger] 记录完成" in log:
            async_logger_end = float(log.split(":")[-1].strip()[:-1])
    
    # 分析同步处理时间
    if bridge_forward and bridge_complete:
        print(f"Bridge转发到完成耗时: {bridge_complete - bridge_forward:.3f}秒")
    
    # 分析同步处理器耗时
    if sync_validator_start and sync_validator_end:
        print(f"同步验证器耗时: {sync_validator_end - sync_validator_start:.3f}秒")
        
    if sync_processor_start and sync_processor_end:
        print(f"同步处理器耗时: {sync_processor_end - sync_processor_start:.3f}秒")
    
    # 分析异步处理器启动时间
    if bridge_forward and async_logger_start:
        print(f"异步处理器启动延迟: {async_logger_start - bridge_forward:.3f}秒")
    
    print("\n关键观察:")
    print("1. 同步处理器会阻塞Bridge的emit调用")
    print("2. 异步处理器在后台执行，不会阻塞主线程")
    print("3. Bridge处理完成的时间点标志着同步处理的结束")
    print("4. 异步处理器在Bridge完成后继续执行")


def main():
    """主函数"""
    demonstrate_sync_async_behavior()


if __name__ == "__main__":
    main()